package org.opendatakit.collect.android.views;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.opendatakit.collect.android.activities.FormEntryActivity;
import org.opendatakit.collect.android.application.Collect;
import org.opendatakit.collect.android.provider.InstanceProviderAPI.InstanceColumns;

import android.database.Cursor;

public class JQueryJavascriptCallback {

	public static final String t = "HtmlJavascriptCallback";
    	
		final FormEntryActivity mActivity; 

        public JQueryJavascriptCallback(FormEntryActivity activity) {
        	mActivity = activity;
    	}
        
    	public void assertValue( String formId, String version, String instanceId, String path, String value ) {
    		mActivity.assertValue(formId, version, instanceId, path, value);
    	}

    	public String getValue( String formId, String version, String instanceId, String path) {
    		return mActivity.getValue(formId, version, instanceId, path);
    	}

    	public static String META_DISPLAY_NAME = "display_name";
    	
    	public String getMetadataValue( String formId, String version, String instanceId, String key ) {
    		Cursor c = null;
            String where = InstanceColumns.INSTANCE_FILE_PATH + "=?";
            String[] whereArgs = {
                Collect.mInstancePath
            };
            
            // the only metadata we support at this time is the display name...
            if ( !key.equals(META_DISPLAY_NAME) ) {
            	return null;
            }
            
            try {
            	c = Collect.getInstance().getContentResolver()
                        .query(InstanceColumns.CONTENT_URI, null, where, whereArgs, null);
            	
            	if ( c.getCount() != 1 ) {
            		// odd... fake the value...
        			return Collect.getInstance().getFormController().getFormTitle();
            	} else {
            		c.moveToFirst();
            		String value = c.getString(c.getColumnIndex(InstanceColumns.DISPLAY_NAME));
            		if ( value == null ) {
            			return Collect.getInstance().getFormController().getFormTitle();
            		}
            		return value;
            	}
            } finally {
            	if ( c != null ) {
            		c.close();
            	}
            }
    	}
    	
    	public void saveCompleted( String formId, String version, String instanceId, final String updatedSaveName, final boolean asComplete ) {
    		// go through the FC because there are additional keys that should be set here...
    		mActivity.saveAllValues(asComplete);
    		
    		// need UI thread so we can show the progress dialog...
    		mActivity.runOnUiThread(new Runnable() {

				@Override
				public void run() {
		    		// and update status as complete or incomplete...
		    		mActivity.saveDataToDisk(asComplete, (updatedSaveName == null || updatedSaveName.trim().length() == 0 ) ? null : updatedSaveName);
					
				}
    			
    		});
    	}
    	
    	public void saveFailed( String formId, String version, String instanceId ) {
    		// need UI thread so we can show the progress dialog...
    		mActivity.runOnUiThread(new Runnable() {

				@Override
				public void run() {
		    		mActivity.cancelSaveDataToDisk();
				}
    			
    		});
    	}
    	
    	public String doAction( String formId, String version, String instanceId, String path, String page, String action, String jsonMap ) {
    		
    		JSONObject valueMap = null;
    		try {
    			if ( jsonMap != null && jsonMap.length() != 0 ) {
    				valueMap = (JSONObject) new JSONTokener(jsonMap).nextValue();
    			}
    		} catch (JSONException e) {
    			e.printStackTrace();
    			return e.toString();
    		}

    		return mActivity.doAction(formId, version, instanceId, path, page, action, valueMap);
    	}
        	
        // Handling Geopoint display
        public static String truncateDouble(double s) {
            DecimalFormat df = new DecimalFormat("#.##");
            return df.format(s);
        }


        public static String formatGps(double coordinates, String type) {
            String location = Double.toString(coordinates);
            String degreeSign = "\u00B0";
            String degree = location.substring(0, location.indexOf(".")) + degreeSign;
            location = "0." + location.substring(location.indexOf(".") + 1);
            double temp = Double.valueOf(location) * 60;
            location = Double.toString(temp);
            String mins = location.substring(0, location.indexOf(".")) + "'";

            location = "0." + location.substring(location.indexOf(".") + 1);
            temp = Double.valueOf(location) * 60;
            location = Double.toString(temp);
            String secs = location.substring(0, location.indexOf(".")) + '"';
            if (type.equalsIgnoreCase("lon")) {
                if (degree.startsWith("-")) {
                    degree = "W " + degree.replace("-", "") + mins + secs;
                } else
                    degree = "E " + degree.replace("-", "") + mins + secs;
            } else {
                if (degree.startsWith("-")) {
                    degree = "S " + degree.replace("-", "") + mins + secs;
                } else
                    degree = "N " + degree.replace("-", "") + mins + secs;
            }
            return degree;
        }
    }